package org.uim.cricket.storage.raise;

import java.util.Collection;
import java.util.Map;

import org.uim.cricket.db.DBThread;
import org.uim.cricket.db.impl.FetchAllSeriesType;
import org.uim.cricket.entities.FullSeries;
import org.uim.cricket.entities.match.CricketMatch;
import org.uim.cricket.entities.match.SeriesPlayed;
import org.uim.cricket.entities.parser.impl.HTMLSeriesPageParser;
import org.uim.cricket.storage.Dlogger;
import org.uim.cricket.storage.backup.BackupFetchedSeries;
import org.uim.cricket.storage.gui.AskNewSeries;
import org.uim.cricket.storage.queries.SeriesQueryGenerator;
import org.uim.cricket.storage.raise.fetch.OrderedFetchList;
import org.uim.cricket.storage.raise.fetch.ResourceFetchable;
import org.uim.cricket.storage.raise.fetch.SeriesArgumentBuilder;

public class InsertNewSeries extends InsertNewEntity {

	public static Collection<String> seriesTypes = null;
	
	private SeriesPlayed series = null;
	private CricketMatch match = null;
	
	public InsertNewSeries(OrderedFetchList rfetcher, CricketMatch match, SeriesPlayed series) {
		super(rfetcher);
		
		this.series = series;
		this.match = match;
	}
	
	public String raise() throws Exception {
		if (series == null) return "";
		String url = null;
		
		if (this.getResourceFetcher() != null) {
			
			SeriesArgumentBuilder sbuilder = new SeriesArgumentBuilder();
			StringBuilder src = null;
			
			for (int i=0; i<this.getSize(); i++) {
				
				try {
					
					url = sbuilder.buildArgument(series);
					ResourceFetchable fetcher = this.getFetcher(i);
					Dlogger.debug("    fetching series page ['" + url + "']..."); 
					src = fetcher.fetchResource(url);
					if (src != null) break;
					
				} catch (Exception ex) {
					
				}
			}
			
			if (src == null) {
				throw new Exception (" * Unable to load official player " + series.getId() + "!");
			}
			
			Dlogger.debug("    backing-up fetched series data to the repository with ID [" + this.series.getId() + "]...");
			new BackupFetchedSeries(src).backup(new String[] {this.series.getId()});
			
			Dlogger.debug("    parsing series page..."); 
			HTMLSeriesPageParser srParser = new HTMLSeriesPageParser();
			FullSeries fs = srParser.parseSeries(src);
			fs.setId(this.series.getId());
			if (fs.getParticipatedCountries() != null) {
				for (String pteam : fs.getParticipatedCountries()) {
					new CheckForCountry().raiseCountry(pteam);
				}
			}
			if (this.series != null) {
				if (this.series.getName() != null) {
					fs.setFullname(match.getSeries().getName());
				}
				if (this.series.getSeason() != null) {
					fs.setSeason(match.getSeries().getSeason());
				}
			} 
			
			if (seriesTypes == null) {
				FetchAllSeriesType fst = new FetchAllSeriesType();
				fst.fetch();
				Map<String, Integer> map = fst.getMap();
				seriesTypes = map.keySet();
			}
			
			AskNewSeries askseries = new AskNewSeries(null, true, fs, seriesTypes, 0);
			askseries.setVisible(true);
			
			String type = "Unknown";
			if (askseries.getSelectedSeriesType() != null) {
				type = askseries.getSelectedSeriesType();
			}
			fs = askseries.getSeries();
			
			String query = new SeriesQueryGenerator(match, fs, type).generateQuery();
			Dlogger.debug(query);
			
			if (query != null && query.length() > 0) {
				Dlogger.debug("       Adding new series to the database...");
				String[] qs = query.split("\n");
				for (int j=0;j<qs.length;j++) {
					qs[j] = qs[j].trim();
					if (qs[j].trim().length() == 0) continue;
					
					DBThread dbt = new DBThread(qs[j].trim()); 
					dbt.run(); dbt.close();
					
				}
				Dlogger.debug("       success.");
			}
			
			askseries.dispose();
			
		} else {
			Dlogger.warn("    unable to locate resource fetcher for series!");
		}
		
		return "";
	}
	
	public void setMatch(CricketMatch match) {
		this.match = match;
	}
	
	public CricketMatch getMatch() {
		return match;
	}

	public void setSeries(SeriesPlayed series) {
		this.series = series;
	}
	
	public SeriesPlayed getSeries() {
		return series;
	}
	
}
